var config = new Config();
var store;
var stats;
config.loadConfiguration(function () {
	console.log("initial configuration", config);
	store = new Store(config);

	 stats = new Stats({
		store: store,
		config:config
	});
	stats.initStats().then(function() {
		stats.initReporter();
	});
});

chrome.storage.onChanged.addListener(function () {
	config.loadConfiguration(function () {
		console.log("configuration changed", config);
		store = new Store(config);
	});
});

var sendToActiveTab = function(request, callback) {
	chrome.tabs.query({
		active: true,
		currentWindow: true
	}, function (tabs) {
		if (tabs.length < 1) {
			this.console.log("couldn't find active tab");
		}
		else {
			var tab = tabs[0];
			chrome.tabs.sendMessage(tab.id, request, callback);
		}
	});
};

chrome.runtime.onMessage.addListener(
	function (request, sender, sendResponse) {
		console.log("chrome.runtime.onMessage", request);
		// alert("backend: "+JSON.stringify(request));
		if (request.createSitemap) {
			store.createSitemap(request.sitemap, sendResponse);
			return true;
		}
		else if (request.saveSitemap) {
			store.saveSitemap(request.sitemap, sendResponse);
			return true;
		}
		else if (request.deleteSitemap) {
			store.deleteSitemap(request.sitemap, sendResponse);
			return true;
		}
		else if (request.getAllSitemaps) {
			store.getAllSitemaps(sendResponse);
			return true;
		}
		else if (request.sitemapExists) {
			store.sitemapExists(request.sitemapId, sendResponse);
			return true;
		}
		else if (request.getSitemapData) {
			store.getSitemapData(new Sitemap(request.sitemap), sendResponse);
			return true;
		}
		else if (request.scrapeSitemap) {
			var sitemap = new Sitemap(request.sitemap);
			// alert("jjjjjjjjjjjjjjjjjjjjjj"+sitemap._id);
			// testUpload(sitemap._id)
			var queue = new Queue();
			var browser = new ChromePopupBrowser({
				pageLoadDelay: request.pageLoadDelay
			});

			var scraper = new Scraper({
				queue: queue,
				sitemap: sitemap,
				browser: browser,
				store: store,
				requestInterval: request.requestInterval,
				stats: stats
			});

			try {
				scraper.run(function () {
					browser.close();
					var notification = chrome.notifications.create("scraping-finished", {
						type: 'basic',
						iconUrl: 'assets/images/icon128.png',
						title: 'Scraping finished!',
						message: 'Finished scraping ' + sitemap._id
					}, function(id) {
						// notification showed
					});
					localStorage.setItem('scraperstatus', '1');
					sendResponse();
				});
			}
			catch (e) {
				console.log("Scraper execution cancelled".e);
			}

			return true;
		}
		else if(request.previewSelectorData) {
			chrome.tabs.query({
				active: true,
				currentWindow: true
			}, function (tabs) {
				if (tabs.length < 1) {
					this.console.log("couldn't find active tab");
				}
				else {
					var tab = tabs[0];
					chrome.tabs.sendMessage(tab.id, request, sendResponse);
				}
			});
			return true;
		}
		else if(request.backgroundScriptCall) {

			var backgroundScript = getBackgroundScript("BackgroundScript");
			var deferredResponse = backgroundScript[request.fn](request.request)
			deferredResponse.done(function(response){
				sendResponse(response);
			});

			return true;
		}
	}
);


// function sleep(ms) {
// 	return new Promise(resolve => setTimeout(resolve, ms));
//   }
// function testUpload2(dbname){
    
//     const BATCH_SIZE = 50;
//     let lastDocKey = null;
// 	// var dbLocation = "sitemap-data-" +  dbname;
// 	alert("testUpload:"+dbLocation);
// 	db = new PouchDB(dbLocation)	
//     async function batchUpload(db) {
//         // alert(db);
//         try {
//             // 1. 使用游标分页查询
// 			let result = null;
// 			while(1){
// 				var scraperstatus =localStorage.getItem('scraperstatus');
// 				result = await db.allDocs({
// 				include_docs: false,
// 				limit: BATCH_SIZE,
// 				startkey: lastDocKey,
// 				skip: lastDocKey ? 1 : 0
// 				});
// 				alert(dbname + "resuit:"+JSON.stringify(result));
// 				// await sleep(10000);
// 				// continue;
// 				if (result.total_rows === 0){
// 					if (scraperstatus == '1'){
// 						alert("break"+scraperstatus);
// 						break;
// 					}
// 					else{
// 						await sleep(10000);
// 					}

// 				} else{
// 					break
// 				}
// 			}

//             // const result = await db.allDocs({include_docs: true});
//             // alert("resuit:"+JSON.stringify(result));
//             // if (result.rows.length === 0) return console.log('所有数据已上传');

//             // 2. 获取完整文档
//             const docs = await Promise.all(
//             result.rows.map(row => db.get(row.id, { attachments: true }))
//             );

//             // 3. 过滤已上传文档
//             const uploadedIds = JSON.parse(localStorage.getItem('uploadedIds') || '[]');
//             const pendingDocs = docs.filter(doc => !uploadedIds.includes(doc._id));

//             // 4. 并行处理文档上传
//             alert("=====================1");
//             await Promise.all(pendingDocs.map(processDocument));

//             // 5. 更新状态
//             alert("=====================2");
//             lastDocKey = result.rows[result.rows.length-1].id;
//             localStorage.setItem('uploadedIds', JSON.stringify([
//             ...uploadedIds,
//             ...pendingDocs.map(doc => doc._id)
//             ]));

//             if (result.rows.length === BATCH_SIZE) batchUpload();
//         } catch (err) {
//             console.error('批量上传失败:', err);
//         }
//     }

//     async function processDocument(doc) {
//             const formData = new FormData();
            
//             // 基础字段
//             // formData.append('title', doc.product_name);
//             // formData.append('img', doc.description);
//             const customFields = Object.keys(doc).reduce((acc, key) => {
// 				if (!key.startsWith('_')) {
// 				  //acc[key] = doc[key];
// 				  formData.append(key, doc[key]);
// 				}
// 				if (key.startsWith('_attach')) {
// 					//acc[key] = doc[key];
// 					formData.append(key, doc[key]);
// 				  }
// 				});
//             // 智能处理图片
//             const imageUrls = [];
            
//             // 处理 Blob 图片
//             // if (doc._attachments) {
//             //     await Promise.all(Object.entries(doc._attachments).map(async ([filename, att]) => {
//             //     if (att.content_type.startsWith('image/')) {
//             //         const blob = att.blob;
//             //         formData.append('images', blob, filename);
//             //         imageUrls.push(`/uploads/${filename}`); // 假设服务端返回这个路径
//             //     }
//             //     }));
//             // }

//         // 处理现有 URL 图片
//         if (doc.imageUrls && Array.isArray(doc.imageUrls)) {
//             imageUrls.push(...doc.imageUrls.filter(url => isValidImageUrl(url)));
//         }

//         // 添加元数据
//         formData.append('metadata', JSON.stringify({
//             _id: doc._id,
//             image_urls: imageUrls
//         }));

//         // 带重试的上传
//         return retryUpload(formData);
//     }
//   //}
    
//     batchUpload(db)
// }
// // 验证图片URL有效性
// function isValidImageUrl(url) {
//   return /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*\.(jpg|jpeg|png|gif)$/i.test(url);
// }

// // 带指数退避的重试
// async function retryUpload(formData, retries = 3) {
//   try {
//     const token = localStorage.getItem('token');
//     const headers = {
//         'Content-Type': 'application/json',
//         'Authorization': `Bearer ${token}`	
//     };
//     const res = await fetch('http://47.121.197.140:82?action=uploaddata', {
//       method: 'POST',
//       body: formData,
//       headers: headers
//     });
//     if (!res.ok) throw new Error('上传失败');
//     return res.json();
//   } catch (err) {
//     if (retries <= 0) throw err;
//     await new Promise(r => setTimeout(r, 1000 * (4 - retries)));
//     return retryUpload(formData, retries - 1);
//   }
// }

  
// function uploadFile(filePath) {
// 	const formData = new FormData();

// 	// 创建文件读取器
// 	const fileReader = new FileReader();

// 	// 使用Chrome文件系统API读取文件
// 	chrome.fileSystem.getDisplayPath(filePath, (fullPath) => {
// 		console.log(`准备上传文件: ${fullPath}`);
// 		const file = new File([fullPath], 'filename');  // 替换为实际的文件对象
// 		formData.append("file", file);

// 		// 上传文件到服务器
// 		fetch("https://your-server.com/upload", {
// 		method: "POST",
// 		body: formData
// 		})
// 		.then(response => response.json())
// 		.then(data => {
// 		console.log('上传成功:', data);
// 		})
// 		.catch(error => {
// 		console.error('上传失败:', error);
// 		});
// 	});
// }
